using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UI_ItemSlot : MonoBehaviour,IPointerDownHandler,IPointerEnterHandler,IPointerExitHandler
{
    protected enum SlotType
    {
        PlayerStorageSlot,
        PlayerInventorySlot,
        PlayerMaterialSlot,
        CraftPlayerinventorySlot,
        MerchantSlot,
    }
    [SerializeField] protected Image itemIcon;
    [SerializeField] protected TextMeshProUGUI itemStackSize;
    [SerializeField] protected SlotType slotType;
    [HideInInspector] public Inventory_Item itemInSlot;
    protected Inventory_Player playerInventory;
    protected UI_ItemToolTip itemToolTip;
    protected RectTransform rect;
    protected UI uI;
    private void Awake()
    {
        playerInventory = FindAnyObjectByType<Inventory_Player>();

        rect = GetComponent<RectTransform>();
        uI = GetComponentInParent<UI>();
    }
    private void Start()
    {
        itemToolTip = GetComponentInParent<UI>().itemToolTip;
    }
    public virtual void OnPointerDown(PointerEventData eventData)
    {
        if (itemInSlot == null || slotType == SlotType.CraftPlayerinventorySlot)
            return;

        bool isClickCtrl = Input.GetKey(KeyCode.LeftControl);
        bool isRightMouseButton = eventData.button == PointerEventData.InputButton.Right;
        if (isClickCtrl && isRightMouseButton)
        {
            playerInventory.RemoveOneItemInOneSlot(itemInSlot);
            return;
        }

        if (itemInSlot.itemData.itemType == ItemType.Consumable)
            playerInventory.TryUseConsumable(itemInSlot);
        else
            playerInventory.TryEquipSlot(itemInSlot);
        
        itemToolTip.ShowToolTip(false, rect, null);
    }
    public virtual void OnPointerEnter(PointerEventData eventData)
    {
        if (itemInSlot == null)
            return;
        itemToolTip.ShowToolTip(true, rect, itemInSlot);
    }

    public virtual void OnPointerExit(PointerEventData eventData)
    {
        if (itemInSlot == null)
            return;
        itemToolTip.ShowToolTip(false, rect, null);
    }

    public virtual void UpdateItemSlot(Inventory_Item inventoryItem)
    {
        itemInSlot = inventoryItem;
        if (inventoryItem == null)
        {
            itemIcon.color = Color.clear;
            itemStackSize.text = "";
            return;
        }
        Color color = Color.white; color.a = .9f;
        itemIcon.color = color;
        itemIcon.sprite = inventoryItem.itemData.itemIcon;

        itemStackSize.text = inventoryItem.stackSize > 1 ? inventoryItem.stackSize.ToString() : "";
    }
}
